package intellitor.sqlparser.ddl.reader;

import intellitor.sqlparser.ddl.DDLReader;
import intellitor.sqlparser.ddl.TableBean;
import intellitor.sqlparser.ddl.exception.BaseException;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


/**
 * 从指定的文件中读取数据定义到TableBean中
 * @author DevilSoul
 * @since 2015-10-27
 * @see ObjReadable
 * @version 1.0.0
 */
public class DDLXLSXReader implements DDLReader {

	private static Logger log = Logger.getLogger(DDLXLSXReader.class);
	
	@Override
	public List<TableBean> read(File obj) throws Exception {
		//返回解析后的表数据
		List<TableBean> tableList = new ArrayList<TableBean>();
		//获取XLSX工作表
		XSSFWorkbook wb = null;
		try {
			if(obj == null){
				throw new BaseException("传入参数为空！");
			}
			//获取XLSX工作表
			wb = new XSSFWorkbook(obj);
			//获取SHEET
			XSSFSheet sheet = wb.getSheetAt(0);
			TableBean bean = null;
			//遍历工作表的行数据
			for(int i = sheet.getFirstRowNum();i<=sheet.getLastRowNum();i++){
				try {
					//当前行
					XSSFRow row = sheet.getRow(i);
					//空行略过
					if(null == row){
						continue;
					}
					//当前行的第一列
					Short curIndex = row.getFirstCellNum();
					XSSFCell cell = row.getCell(curIndex);
					//第一列的数据
					String cellValue = cell.getStringCellValue();
					//解析数据定义数据
					switch(cellValue){
						//表名（EN）
						case "表名（EN）":
							bean = new TableBean();
							tableList.add(bean);
							//表的英文列集合
							bean.setTableColumnsList(new ArrayList<String>());
							//表的列中文MAP，KEY=英文列名，VALUE=中文列名
							bean.setTableColumnsCnMap(new HashMap<String, String>());
							//表的列约束MAP，KEY=英文列名，VALUE=约束名
							bean.setTableConstraintsMap(new HashMap<String, String>());
							//表的注解MAP，KEY=英文列名，VALUE=注解
							bean.setTableCommentsMap(new HashMap<String, String>());
							//表的列类型MAP，KEY=英文列名，VALUE=列类型
							bean.setTableColumnTypeMap(new HashMap<String, String>());
							//表的列操作类型MAP,KEY=英文列名，VALUE=操作类型
							bean.setTableColumnOpTypeMap(new HashMap<String, String>());
							//表的默认值MAP，KEY=英文列名，VALUE=默认值
							bean.setTableColumnDefaultValueMap(new HashMap<String, String>());
							
							bean.setTableNameEN(row.getCell(curIndex+1).getStringCellValue());
							break;
						//表名（CN）
						case "表名（CN）":
							bean.setTableNameCN(row.getCell(curIndex+1).getStringCellValue());
							break;
						//操作
						case "操作":
							bean.setTableOpType(row.getCell(curIndex+1).getStringCellValue());
							break;
						//描述
						case "描述":
							bean.setTableDesc(row.getCell(curIndex+1).getStringCellValue());
							break;
						//序列
						case "序列":
							bean.setTableSeq(row.getCell(curIndex+1).getStringCellValue());
							break;
						//表头，忽略不处理
						case "字段名称":
							break;
						//空行，忽略
						case "":
							break;
						default:
							//非空行处理
							if(null != cellValue){
								//英文列名
								bean.getTableColumnsList().add(cellValue);
								//中文名称
								bean.getTableColumnsCnMap().put(cellValue, row.getCell(curIndex+1).getStringCellValue());
								//数据类型及长度
								bean.getTableColumnTypeMap().put(cellValue, row.getCell(curIndex+2).getStringCellValue());
								//约束
								bean.getTableConstraintsMap().put(cellValue, row.getCell(curIndex+3).getStringCellValue());
								//默认值
								bean.getTableColumnDefaultValueMap().put(cellValue, row.getCell(curIndex+4).getStringCellValue());
								//备注
								bean.getTableCommentsMap().put(cellValue, row.getCell(curIndex+5).getStringCellValue());
								//操作
								bean.getTableColumnOpTypeMap().put(cellValue, row.getCell(curIndex+6).getStringCellValue());
							}
							break;
					}
				} catch (Exception e) {
					String info = "处理第"+(i+1)+"行时发生异常！";
					log.error(info,e);
					throw new BaseException(info);
				}
			}
		} catch (IOException e){
			log.error("文件解析IO异常！",e);
			throw new BaseException("数据定义文件读取异常！");
		} catch (InvalidFormatException e) {
			log.error("文件格式不合法异常！",e);
			throw new BaseException("数据定义文件格式异常！");
		}finally{
			if(null != wb){
				try {
					wb.close();
				} catch (IOException e) {
					log.error("文件关闭异常！"+e,e);
				}
			}
		}
		return tableList;
	}

}
